﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LuaInterface;

public class LuaManager : MonoBehaviour
{
    public bool IsDebug = false;
    public static LuaManager Instance { get; private set; }
    public LuaState LuaState { get; private set; }

    private LuaLoader loader;
    private LuaLooper loop = null;

    private void Awake()
    {
        Instance = this;
  
        if (IsDebug)
        {
            InitStart();
        }

        DontDestroyOnLoad(this.gameObject);
    }

    public void InitStart()
    {
        loader = new LuaLoader();
        LuaState = new LuaState();

        this.OpenLibs();
        LuaState.LuaSetTop(0);

        LuaBinder.Bind(LuaState);
        // 这里将unity的协程注册到Lua中调用
        LuaCoroutine.Register(LuaState, this);

        InitLuaPath();
        InitLuaBundle();

        this.LuaState.Start();
        this.StartLooper();

        //lua.Require("Function");
    }

    public void LuaGC()
    {
        LuaState.LuaGC(LuaGCOptions.LUA_GCCOLLECT);
    }

    public void Close()
    {
        LuaGC();

        loop.Destroy();
        loop = null;

        LuaState.Dispose();
        LuaState = null;
        loader = null;
    }

    private void StartLooper()
    {
        loop = gameObject.AddComponent<LuaLooper>();
        loop.luaState = LuaState;
    }

    /// <summary>
    /// 初始化加载第三方库
    /// </summary>
    private void OpenLibs()
    {
        OpenCJson();
    }

    //cjson 比较特殊，只new了一个table，没有注册库，这里注册一下
    private void OpenCJson()
    {
        LuaState.LuaGetField(LuaIndexes.LUA_REGISTRYINDEX, "_LOADED");
        LuaState.OpenLibs(LuaDLL.luaopen_cjson);
        LuaState.LuaSetField(-2, "cjson");

        LuaState.OpenLibs(LuaDLL.luaopen_cjson_safe);
        LuaState.LuaSetField(-2, "cjson.safe");
    }

    /// <summary>
    /// 初始化Lua代码加载路径
    /// </summary>
    private void InitLuaPath()
    {
        if (AppConst.DebugMode)
        {
            LuaState.AddSearchPath(Application.dataPath + "/Lua");
            LuaState.AddSearchPath(Application.dataPath + "/ToLua/Lua");
        }
        else
        {
            LuaState.AddSearchPath(Util.DataPath + "lua");
        }
    }

    /// <summary>
    /// 初始化LuaBundle,这里也就是添加查找路径
    /// </summary>
    private void InitLuaBundle()
    {
        if (loader.beZip)
        {
            loader.AddBundle("lua/lua_cjson.unity3d");
            loader.AddBundle("lua/lua_jit.unity3d");
            loader.AddBundle("lua/lua_lpeg.unity3d");
            loader.AddBundle("lua/lua_misc.unity3d");
            loader.AddBundle("lua/lua_protobuf.unity3d");
            loader.AddBundle("lua/lua_socket.unity3d");
            loader.AddBundle("lua/lua_system.unity3d");
            loader.AddBundle("lua/lua_system_reflection.unity3d");
            loader.AddBundle("lua/lua_unityengine.unity3d");

            loader.AddBundle("lua/lua.unity3d");
            loader.AddBundle("lua/lua_test.unity3d");
        }
    }
}
